# -*- coding: utf-8 -*-
import json
import random
from scrapy import Request
from zc_core.dao.batch_dao import BatchDao
from zc_core.dao.item_data_dao import ItemDataDao
from iccec.rules import parse_supplier, parse_supplier_id
from zc_core.util.done_filter import DoneFilter
from zc_core.spiders.base import BaseSpider


class priceSpider(BaseSpider):
    name = 'supplier'
    custom_settings = {
        'CONCURRENT_REQUESTS': 32,
        'CONCURRENT_REQUESTS_PER_DOMAIN': 32,
        'CONCURRENT_REQUESTS_PER_IP': 32,
    }
    # 搜索引擎
    supplier_url = 'https://emos.iccec.cn/apis/emos/cc/users/signup/searchProp'
    supplier_id_url = 'https://emos.iccec.cn/apis/emos/cc/users/signup/searchBoxList'

    def __init__(self, batchNo=None, *args, **kwargs):
        super(priceSpider, self).__init__(batchNo=batchNo, *args, **kwargs)
        # 创建批次记录
        BatchDao().create_batch(self.batch_no)
        # 避免重复采集
        self.done_filter = DoneFilter(self.batch_no)
        self.page_size = 1

    def start_requests(self):

        yield Request(
            method='POST',
            url=self.supplier_url,
            meta={
                'reqType': 'supplier',
                'batchNo': self.batch_no,
            },
            body=json.dumps({"pageNo": 1, "pageSize": 1, "skuStatus": 2, "isCheck": True, "qryStr": "", "active": 0,
                             "province": "1", "city": "2802", "county": "2821", "town": "0", "agentId": 100106}),
            headers={
                'Content-Type': 'application/json;charset=UTF-8'
            },
            callback=self.parse_supplier_code,
            errback=self.error_back,
        )

    # 处理ItemData
    def parse_supplier_code(self, response):
        meta = response.meta
        batch_no = meta.get('batchNo')
        data = parse_supplier(response)
        for name, code in data:
            yield Request(
                method='POST',
                url=self.supplier_id_url,
                meta={
                    'reqType': 'supplier',
                    'batchNo': self.batch_no,
                    'name': name,
                    'code': code,
                    'batcNo': batch_no
                },
                body=json.dumps(
                    {"pageNo": 1, "pageSize": self.page_size, "skuStatus": 2, "isCheck": True, "qryStr": "",
                     "active": 0,
                     "province": "1", "city": "2802", "county": "2821", "town": "0", "agentId": 100106,
                     "filterConditions": [{"type": "shop", "paramList": [code]}],
                     "propConditions": [{"type": "properties", "paramList": []}], "propertiesShowTag": {}}),
                headers={
                    'Content-Type': 'application/json;charset=UTF-8'
                },
                callback=self.parse_supplier_id,
                errback=self.error_back,
            )

    def parse_supplier_id(self, response):
        data = parse_supplier_id(response)
        if data:
            self.logger.info('供应商: supplierName=%s, supplierId=%s' % (data.get('name'), data.get('id')))
            yield data
        else:
            self.logger.info('供应商ID获取失败: [%s]' % response.meta.get('name'))
